<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <input type="text" id="username"> <input type="checkbox" name="" id="remember"> 记住用户名
    <script>
        // var username = document.querySelector('#username');
        // var remember = document.querySelector('#remember');
        // if (localStorage.getItem('username')) {
        //     username.value = localStorage.getItem('username');
        //     remember.checked = true;
        // }
        // remember.addEventListener('change', function() {
        //     if (this.checked) {
        //         localStorage.setItem('username', username.value)
        //     } else {
        //         localStorage.removeItem('username');
        //     }
        // })


        // 课堂练习
        // 获取
        // var username = document.querySelector('#username');
        // var remember = document.querySelector('#remember');
        // // 当存储里面能拿到username，则将拿到的值赋值给username，复选框选中
        // if (localStorage.getItem('username')) {
        //     username.value = localStorage.getItem('username');
        //     remember.checked = true;

        // }
        // // 当复选框有变化时候，判断复选框选中，则保存；否则删除
        // remember.addEventListener('change', function () {
        //         if (this.checked) {
        //             localStorage.setItem('username', username.value)
        //         } else {
        //             localStorage.removeItem('username');
        //         }
        //     })

        var username = document.querySelector('#username');
        var remember = document.querySelector('#remember');

        if (localStorage.getItem('username')) {
            remember.value = localStorage.getItem('username');
            remember.checked = true;
        }
        remember.addEventListener('change', function () {
            if (this.checked) {
                localStorage.setItem('username', username.value);

            } else {
                localStorage.removeItem('username')
            }
        })



    </script>
</body>